﻿using ECMS.Api.Token;
using ECMS.AppService.Interfaces;
using ECMS.AppService.Model.Requests.AppUser;
using ECMS.AppService.Model.Responses;
using ECMS.Infrastructure.ClientData;
using ECMS.Infrastructure.Const;
using ECMS.Infrastructure.Helper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using System.Threading.Tasks;

namespace ECMS.API.Controllers
{
    /// <summary>
    /// 登录文档
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : BaseController
    {
        private readonly IHttpContextAccessor _accessor;
        private readonly IAppUserService _appService;
        private readonly ILoggerFactory _loggerFactoryk;


        public AccountController(IAppUserService userService, IHttpContextAccessor accessor, ILoggerFactory loggerFactory)
        {
            _appService = userService;
            _accessor = accessor;
            _loggerFactoryk = loggerFactory;

        }

        #region Handle
        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<ApiResult<AppUserResponse>> ValidateLogin([FromBody]LoginRequest request)
        {
            var response = await _appService.LoginAsync(request);

            try
            {
                if (response.Success)
                {
                    await SignInAsync(response.Data);

                    TokenResponse token = await GetTokenAsync(request.LoginName, request.Password);

                    if (token == null)
                    {
                        return new ApiResult<AppUserResponse>()
                        {
                            Message = "认证失败",
                            StatusCode = 200,
                            Success = false
                        };
                    }
                    response.Data.Token = token;
                }
                //更新登录时间
                await _appService.UpdateLastLoginTime(response.Data.Guid);
            }
            catch (Exception e)
            {
                new Logger("用户登录错误").Error(e.Message);
            }

            return response;
        }

        /// <summary>
        /// 注册接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("Register")]
        
        public async Task<ApiResult<AppUserResponse>> ValidateRegister([FromBody]RegisterRequest request)
        {
            var response = new ApiResult<AppUserResponse>();

            response = await _appService.RegisterAsync(request);
            try
            {
                if (response.Success)
                {
                    await SignInAsync(response.Data);

                    TokenResponse token = await GetTokenAsync(request.Mobile, request.Password);

                    if (token == null)
                    {
                        return new ApiResult<AppUserResponse> { Success = false, Data = null, Message = "令牌失效", StatusCode = 200 };
                    }
                    response.Data.Token = token;
                }
            }
            catch (Exception e)
            {
                new Logger("用户注册错误").Error(e.Message);
                new ApiResult<AppUserResponse> { Success = false, Data = null, Message = "异常错误", StatusCode = 200 };
            }

            return response;
        }


        #endregion


        #region Token
        private async Task<TokenResponse> GetTokenAsync(string loginname, string password)
        {
            var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.secretKey));
            var options = new TokenProviderOptions
            {
                Audience = "appuser",
                Issuer = "djkj",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
            };
            var tpm = new TokenProvider(options, _appService);
            var token = await tpm.GenerateToken(HttpContext, loginname, password, "appuser");
            return token;
        }

        #endregion

    }
}
